package com.cms.server.resolver.plugins;

import java.sql.ResultSet;

import com.efounder.builder.base.data.DataSetUtils;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.data.JParamObject;
import com.efounder.form.EFFormDataModel;
import com.efounder.form.io.FormDataResolverAdapter;
import com.efounder.sql.JStatement;

public class CMSYTHTFKJECheck extends FormDataResolverAdapter {

	public void prepareSaveForm(JStatement stmt, EFFormDataModel model, JParamObject PO) throws Exception {
		EFDataSet                    billDataSet = model.getBillDataSet();
		EFRowSet                        htRowSet;
		EFRowSet                  headItemRowSet;
		Double                              fkje = 0.0;
		Double                              htje = 0.0;
		Double                              ljje = 0.0;
		String                          errorMsg = "";
		
		if(billDataSet.getRowCount() > 0) {
			headItemRowSet = billDataSet.getRowSet(0);
			fkje = (Double) headItemRowSet.getNumber("F_FKJE", 0.0);
			htRowSet = getHTRow(stmt, headItemRowSet.getString("F_HTBH", ""));
			htje = htRowSet.getNumber("F_HTJE", null).doubleValue();
			ljje = (Double) htRowSet.getNumber("F_LJJE", null);
			
			if(htje == null) htje = 0.0;
			
			if(htje < fkje + ljje) {
				errorMsg = "合同" + htRowSet.getString("F_HTMC", "") + "金额为：" + htje + ";已付款：" + ljje + ";\r\n"
				         + "所以本次付款金额加累计金额超过合同金额，请重新维护本次付款金额！";
				throw new Exception(errorMsg);
			}
		}
	}
	
	private Double parseDouble(String s) {
		try {
			return Double.parseDouble(s);
		} catch(Exception ce) {
			return 0.0;
		}
	}
	
	private EFRowSet getHTRow(JStatement stmt, String F_HTBH) throws Exception {
		ResultSet          rs = null;
		String         strSql = "";
		EFDataSet     dataset = EFDataSet.getInstance("HTZDMX");
		EFRowSet       rowset = EFRowSet.getInstance();
		Double           fkje = 0.0;
		
		strSql = "select F_HTBH,F_HTMC,F_HTJE from HTXXZD where F_HTBH = '" + F_HTBH + "'";

		rs = stmt.executeQuery(strSql);
		dataset = DataSetUtils.resultSet2DataSet(rs, dataset);
		rowset = dataset.getRowSet(0);
		
		strSql = "select round(sum(F_FKJE),2) as F_LJJE from HTFKXX where F_HTBH = '" + F_HTBH + "' and F_DJZT = '1'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) {
			fkje = rs.getDouble("F_LJJE");
		}
		rowset.putNumber("F_LJJE", fkje);
		
		return rowset;
	}
}
